package com.example.http.controller;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.util.HashMap;
import java.util.Map;

/**
 * @author jie
 * @date 2021/5/6 -16:52
 */
@RestController
public class TestController {

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/test01")
    public void test01() throws Exception {

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        Map<String, Object> body = new HashMap<>();
        body.put("name","jie");
        body.put("id","21");
        HttpEntity<Object> httpEntity = new HttpEntity<>(JSONObject.toJSON(body),headers);
        ResponseEntity<String> strBody = restTemplate.exchange("http://10.0.0.132:8081/hello", HttpMethod.POST, httpEntity, String.class);
        JSONObject jsonObject = JSONObject.parseObject(strBody.getBody());
        System.out.println(jsonObject);
    }

    @GetMapping("/test02")
    public void test02() throws Exception {

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<Object> httpEntity = new HttpEntity<>(headers);

        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("http://10.0.0.132:8081/hello")
                .queryParam("name","jie");

        ResponseEntity<String> response  = restTemplate.exchange(builder.toUriString(), HttpMethod.GET, httpEntity, String.class);
        JSONObject jsonObject = JSONObject.parseObject(response.getBody());
        System.out.println(jsonObject);
    }
}
